<?php

namespace App\Jobs\Posts;

use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsVideo;
use App\Wen\Utils\PostUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UpdatePostVideoIdJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $post_id = 0;
    public $tries = 1;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($post_id)
    {
        //
        $this->post_id = $post_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        if(_empty_($this->post_id)){
            $post_ids = WxPost::whereNull('video_id')->orderBy('id', 'desc')->limit(50)->pluck('id')->toArray();
            if($post_ids){
                $no_video_posts = [];
                foreach ($post_ids as $post_id){
                    $video_id = WxPostsVideo::where('posts_id', $post_id)->value('id');
                    if($video_id > 0){
                        WxPost::withoutSyncingToSearch(function () use ($post_id,$video_id){
                            WxPost::where('id', $post_id )->update(['video_id'=>$video_id]);
                        });
                    }else{
                        $no_video_posts[] = $post_id;
                    }
                }
                if(!_empty_($no_video_posts)){
                    WxPost::withoutSyncingToSearch(function () use ($no_video_posts){
                        WxPost::whereIn('id', $no_video_posts )->update(['video_id'=>0]);
                    });
                }
            }
        }else{
            $video_id = WxPostsVideo::where('posts_id', $this->post_id)->value('id');
            if($video_id > 0){
                WxPost::withoutSyncingToSearch(function () use ($video_id){
                    WxPost::where('id', $this->post_id )->update(['video_id'=>$video_id]);
                });
            }else{
                WxPost::withoutSyncingToSearch(function (){
                    WxPost::where('id', $this->post_id )->update(['video_id'=>0]);
                });
            }
        }


    }
}
